package com.handu.apollo.config.service.proxy;

import com.google.common.base.Preconditions;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class RefreshableProxy<T> implements MethodInterceptor {
	private T target;
	private final T proxy;

	public RefreshableProxy(final T target) {
		this.target = (T) Preconditions.checkNotNull((Object) target);
		final Enhancer enhancer = new Enhancer();
		enhancer.setSuperclass(this.target.getClass());
		enhancer.setCallback(this);
		this.proxy = (T) enhancer.create();
	}

	public void refresh(final T target) {
		this.target = (T) Preconditions.checkNotNull((Object) target);
	}

	public T getInstance() {
		return this.proxy;
	}

	@Override
	public Object intercept(final Object obj, final Method method, final Object[] args, final MethodProxy proxy)
			throws Throwable {
		return proxy.invoke(this.target, args);
	}
}
